import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';
import { CacheService } from './cache.service';
import { NetService } from './net.service';
import { NzMessageService } from 'ng-zorro-antd';
import { env } from '../../environments/index';
@Injectable({
  providedIn: 'root'
})
export class SocketService {
  private url = env.socket;
  private userList = [];
  private updateTime: number;
  public socket: any;
  public socketState: string;
  public clientCounts = 0;
  constructor(
    private cacheService: CacheService,
    private mzmsg: NzMessageService,
    private net: NetService
  ) {}

  async init() {
    const userInfo = await this.cacheService.getUserInfo();
    if (!userInfo) { return; }
    const uid = userInfo['_id'];
    const name = userInfo['nickName'];
    this.socket = io(`${this.url}?uid=${uid}&name=${name}`);

    this.socket.on('connect', () => {
      this.socketState = 'ok';
      // console.log('this.socketState: ' + this.socketState);
    });

    this.socket.on('disconnect', () => {
      if (!this.cacheService.isLogin) { return; }
      this.socketState = 'no';
      // console.log('this.socketState: ' + this.socketState);
    });

    this.socket.on('error', () => {
      if (!this.cacheService.isLogin) { return; }
      this.socketState = 'error';
      // console.log('this.socketState: ' + this.socketState);
    });

    this.socket.on('clientCounts', data => {
      if (!this.cacheService.isLogin) { return; }
      this.clientCounts = data;
      // console.log('this.socketState: ' + this.socketState);
    });

    this.socket.on('login', async data => {
      if (!this.cacheService.isLogin) { return; }
      this.clientCounts = data.clientCounts;
      const info = await this.cacheService.getUserInfo();
      if (data.uid !== info['_id']) {
        this.mzmsg.info(data.name + ' 已登陆！');
      }
    });

    this.socket.on('logout', async data => {
      if (!this.cacheService.isLogin) { return; }
      this.clientCounts = data.clientCounts;
      this.mzmsg.info(data.name + ' 已退出登陆!');
    });
  }

  sendMsg(type, msg) {
    this.socket.emit(type, msg);
  }

  close() {
    this.socket.close();
    this.socket = null;
  }

  async getUserList() {
    if (this.updateTime && ((this.updateTime - 60 * 1000) < new Date().valueOf())) {
      return this.userList;
    } else {
      const result = await this.net.get('/api/users');
      if (result) {
        this.userList = result['data'];
      }
      return this.userList;
    }
  }

}
